package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.User;

import utils.HibernateUtil;




public class UserDao {
	private SessionFactory sessionFactory;

	public UserDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;

	/**
	 * 删除用户
	 */
	public void delete(User user) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(user);
		tr.commit();
		session.close();
	}

	/**
	 * 修改用户
	 */
	public void edit(User user) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(user);
		tr.commit();
		session.close();
	}

	/**
	 * 保存新增的用户
	 */
	public void save(User user) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(user);
		tr.commit();
		session.close();
	}

	/**
	 * 返回所有用户信息
	 */
	public List<User> getAllUser() {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(User.class);
		c.add(Restrictions.ne("status", "0"));
		List<User> users = c.list();
		tr.commit();
		session.close();
		return users;
	}
	
	/**
	 * 根据微信ID查找用户
	 */
	public List<User> getUserByWxID(String wxID) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(User.class);
		c.add(Restrictions.eq("wxID", wxID));
		List<User> users = c.list();
		tr.commit();
		session.close();
		return users;
	}

	/**
	 * 筛选手机号码返回用户信息
	 */
	public List<User> getAllUserPhoneNum(String phoneNum) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Criteria c = session.createCriteria(User.class);
		c.add(Restrictions.eq("mobileNum", phoneNum));
		List<User> users = c.list();
		tr.commit();
		session.close();
		return users;
	}

	/**
	 * 通过公司ID返回指定用户信息
	 * 
	 * @return
	 */
	public User getUserById(int userId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		User user = (User) session.get(User.class, userId);
		tr.commit();
		session.close();
		return user;
	}
}
